#include "iostream"
#include "stdlib.h"
 
#include "cv.h"
#include "highgui.h"
 
using namespace std;
int motion(IplImage* colourImage){ // Kameradan gelen Frame olacak!!!!!!!

    int say;
     bool first = true;
     CvSize imgSize;
 imgSize.width = 640;
 imgSize.height = 480;
    IplImage* greyImage = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);
 IplImage* colourImage=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* movingAverage = cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* difference=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 IplImage* temp=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
 difference = cvCreateImage( imgSize, IPL_DEPTH_8U, 3);

 
  //If there are no more frames, jump out of the for.
 // if( !colourImage )
 // {
 //  break;
 // }
  
  if(first)
  {
   difference = cvCloneImage(colourImage);
   temp = cvCloneImage(colourImage);
   cvConvertScale(colourImage, movingAverage, 1.0, 0.0);
   first = false;
  }
  //else, make a running average of the motion.
  else
  {
   cvRunningAvg(colourImage, movingAverage, 0.020, NULL);
  }
 
  //Convert the scale of the moving average.
  cvConvertScale(movingAverage,temp, 1.0, 0.0);
 
  //Minus the current frame from the moving average.
  cvAbsDiff(colourImage,temp,difference);
  
  //Convert the image to grayscale.
  cvCvtColor(difference,greyImage,CV_RGB2GRAY);
  
  //Convert the image to black and white.
  cvThreshold(greyImage, greyImage, 70, 255, CV_THRESH_BINARY);
  
  //Dilate and erode to get people blobs
  cvDilate(greyImage, greyImage, 0, 10);
  cvErode(greyImage, greyImage, 0, 10);
   cvShowImage("My Window", greyImage);
   say=cvCountNonZero(greyImage);

  if(38400<=say){
        cout<<"Hareket var\n "<<say<<"\n";       
  return 1;                   
  }else{
  return 0;
  }
  //Wait for the user to see it.
//  cvWaitKey(5);
  
//}
 cvReleaseImage(&temp);
 cvReleaseImage(&difference);
 cvReleaseImage(&greyImage);
 cvReleaseImage(&colourImage);
    
    }
